<?php

session_cache_limiter("nocache");
require_once('../utilidades/ConexionBD.php');

class GestionBoleta {

    public static function GetAccumulated($idClient){
        $query = "SELECT \"acumulado\" FROM \"MaeCliente\" WHERE id = " . $idClient;
        $result = pg_query(ConexionBD::get()->conectarse(), $query);
        
        if (!$result) {
            return json_encode(array("ERROR" => str_replace("ERROR:", "", pg_last_error(ConexionBD::get()->conectarse()))));
        }
        
        $row = pg_fetch_array($result);
        
        return json_encode($row["acumulado"]);
    }
    
    public static function GetDrawValue($idSorteo){
        $query = "SELECT \"valorSorteo\" FROM \"MaeSorteo\" WHERE id = " . $idSorteo;
        $result = pg_query(ConexionBD::get()->conectarse(), $query);
        
        if (!$result) {
            return json_encode(array("ERROR" => str_replace("ERROR:", "", pg_last_error(ConexionBD::get()->conectarse()))));
        }
        
        $row = pg_fetch_array($result);
        
        return json_encode($row["valorSorteo"]);
    }
    
    public static function CheckClient($nameOrId) {
        $query = "SELECT \"id\", \"codMaeCliente\", \"nombreMaeCliente\" FROM \"MaeCliente\" WHERE \"codMaeCliente\" LIKE '%" . $nameOrId . "%' OR \"nombreMaeCliente\" LIKE '%" . strtoupper($nameOrId) . "%' LIMIT 10";
        $result = pg_query(ConexionBD::get()->conectarse(), $query);

        if (!$result) {
            return json_encode(array("ERROR" => str_replace("ERROR:", "", pg_last_error(ConexionBD::get()->conectarse()))));
        }
        
        $users = array();
        while ($row = pg_fetch_array($result)) {
            $users["users"][] = array("id" => $row["id"],
                "name" => $row["nombreMaeCliente"],
                "cc" => $row["codMaeCliente"]
                );
        }
        return json_encode($users);
    }

    public static function GenerateTicket($codUsuario, $idClient, $sorteo, $empresa, $numFactura, $valFactura) {

        $total_paied = array_sum($valFactura);

        $get_draw_value = "SELECT \"id\", \"valorSorteo\" FROM \"MaeSorteo\" WHERE \"id\" = " . $sorteo;
        $result_1 = pg_query(ConexionBD::get()->conectarse(), $get_draw_value);

        if (!$result_1) {
            return json_encode(array("ERROR" => str_replace("ERROR:", "", pg_last_error(ConexionBD::get()->conectarse()))));
        }

        $row_sorteo = pg_fetch_array($result_1);

        $get_client_info = "SELECT \"id\", \"acumulado\", \"nombreMaeCliente\", \"telefono\", \"eMail\", \"codMaeCliente\" FROM \"MaeCliente\" WHERE \"id\" = '" . $idClient . "'";
        $result_2 = pg_query(ConexionBD::get()->conectarse(), $get_client_info);

        if (!$result_2) {
            return json_encode(array("ERROR" => str_replace("ERROR:", "", pg_last_error(ConexionBD::get()->conectarse()))));
        }

        $row_cliente = pg_fetch_array($result_2);

        for ($i = 0; $i < count($numFactura); $i++) {
            if (!empty($numFactura[$i])) {
                $query_insert_bill = "INSERT INTO \"FacturaCliente\" (\"usuarioGrab\", \"idMaeCliente\", \"numeroFactura\", \"idMaeSorteo\", \"codMaeEmpresa\", \"valorFactura\")"
                        . "VALUES ('" . $codUsuario . "', " . $row_cliente["id"] . ", '" . $numFactura[$i] . "', " . $row_sorteo["id"] . ", '" . $empresa[$i] . "', " . $valFactura[$i] . ")";
                $result = pg_query(ConexionBD::get()->conectarse(), $query_insert_bill);
                if (!$result) {
                    return json_encode(array("ERROR" => str_replace("ERROR:", "", pg_last_error(ConexionBD::get()->conectarse()))));
                }
            }
        }

        $number_tickets = floor(($total_paied + $row_cliente["acumulado"]) / $row_sorteo["valorSorteo"]);
        $tickets = array();

        for ($i = 0; $i < $number_tickets; $i++) {
            $query_insert_ticket = "INSERT INTO \"BoletaCliente\" (\"usuarioGrab\", \"idMaeCliente\", \"idMaeSorteo\")"
                    . "VALUES ('" . $codUsuario . "', " . $row_cliente["id"] . ", " . $row_sorteo["id"] . ")";
            $result = pg_query(ConexionBD::get()->conectarse(), $query_insert_ticket);

            if (!$result) {
                return json_encode(array("ERROR" => str_replace("ERROR:", "", pg_last_error(ConexionBD::get()->conectarse()))));
            }

            // get last id inserted
            $query_select_last_id = "SELECT \"id\" FROM \"BoletaCliente\" ORDER BY \"id\" DESC LIMIT 1";
            $result_3 = pg_query(ConexionBD::get()->conectarse(), $query_select_last_id);

            if (!$result_3) {
                return json_encode(array("ERROR" => str_replace("ERROR:", "", pg_last_error(ConexionBD::get()->conectarse()))));
            }

            $id_ticket = pg_fetch_array($result_3);

            $tickets[] = $id_ticket["id"];
        }

        $accumulated = ($total_paied + $row_cliente["acumulado"]) - $number_tickets * $row_sorteo["valorSorteo"];

        $query_update_accumulated = "UPDATE \"MaeCliente\" SET \"acumulado\" = " . $accumulated . " WHERE \"id\" = " . $row_cliente["id"];
        pg_query(ConexionBD::get()->conectarse(), $query_update_accumulated);

//        $finalResul = array(
//                    "numberTickets" => $number_tickets,
//                    "tickets" => $tickets,
//                    "accumulated" => $accumulated,
//                    "beforeAccumulated" => $row_cliente["acumulado"],
//                    "total" => $total_paied,
//                    "draw_value" => $row_sorteo["valorSorteo"],
//                    "client_name" => $row_cliente["nombreMaeCliente"],
//                    "phone" => $row_cliente["telefono"],
//                    "email" => $row_cliente["eMail"],
//                    "id" => $row_cliente["codMaeCliente"]
//        );
        
        GestionBoleta::PrintTickets($row_cliente["codMaeCliente"], $row_cliente["nombreMaeCliente"], $row_cliente["telefono"], $row_cliente["eMail"], $tickets);
        
    }

    private static function PrintTickets($id, $clientName, $phone, $email, $tickets) {
        
        require_once('../utilidades/fpdf.php');

        $pdf = new FPDF('P', 'mm', array(75, 100));
        
        for ($i = 0; $i < count($tickets); $i++) {
            $pdf->AddPage();
            $pdf->SetFont('Arial', 'B', 14);
            $pdf->Image('../recursos/imagenes/logo.png', 7, 5);
            $pdf->SetY(20);
            $pdf->SetLeftMargin(5);
            $pdf->SetRightMargin(5);
            $pdf->Write(8, 'Boleta # ');
            $pdf->SetFontSize(20);
            $pdf->Write(8, $tickets[$i]);
            $pdf->Ln();
            $pdf->SetFontSize(14);
            $pdf->Write(8, 'Telefono: ');
            $pdf->Write(8, $phone);
            $pdf->Ln();
            $pdf->SetFontSize(14);
            $pdf->Write(8, 'email: ');
            $pdf->Write(8, $email);
            $pdf->Ln();
            $pdf->Write(8, 'Cedula: ');
            $pdf->Write(8, $id);
            $pdf->Ln();
            $pdf->SetFontSize(8);
            $pdf->Write(8, $clientName);
            $pdf->SetXY(20, -28);
            $pdf->SetFont('Arial', 'I', 8);
            $pdf->Write(1, 'www.fgtegnologiayservicios.com');
            $pdf->SetXY(8, -25);
            $pdf->SetFont('Arial', 'I', 6);
            $pdf->Write(1, '______________________________________________');
        }
        $pdf->Output();
    }

}
